package ld.oauth.blog.service.user.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ld.common.ResultInfoFactory;
import ld.oauth.blog.mapper.user.SysRoleMapper;
import ld.oauth.blog.mapper.user.SysUserMapper;
import ld.oauth.blog.model.bo.CheckOldPasswordBo;
import ld.oauth.blog.model.bo.SysUserBo;
import ld.oauth.blog.model.po.user.SysRole;
import ld.oauth.blog.model.po.user.SysUser;
import ld.oauth.blog.model.qo.UserArticleQo;
import ld.oauth.blog.model.vo.UserArticleVo;
import ld.oauth.blog.model.vo.UserQuestionVo;
import ld.oauth.blog.service.user.SysUserService;
import ld.oauth.blog.utils.PageResult;
import ld.oauth.blog.utils.PageUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author
 * @since 2022-08-29
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    private static final String DEFAULT_PASSWORD = "$2a$10$rDkPvvAFV8kqwvKJzwlRv.i.q.wz1w1pz0SFsHn/55jNeZFQv/eCm";

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;


    @Override
    public Boolean deleteByUserId(Long userId) {
        SysUser sysUser = baseMapper.selectById(userId);
        sysUser.setIsEnabled(false);
        sysUser.setUpdateDate(LocalDateTime.now());
        baseMapper.updateById(sysUser);
        return true;
    }

    @Override
    public boolean saveOrUpdate(SysUser entity) {
        if (entity.getId() == null) {
            entity.setPassword(DEFAULT_PASSWORD);
        }
        boolean flag = super.saveOrUpdate(entity);
        if (flag) {
            //先删除
            baseMapper.deleteUserRoleByUserId(entity.getId());
            if (!CollectionUtils.isEmpty(entity.getRoleIds())) {
                baseMapper.saveUserRole(entity.getId(), entity.getRoleIds());
            }
        }
        return super.saveOrUpdate(entity);
    }

    @Override
    public SysUser findById(Long id) {
        if (id == null) {
            return new SysUser();
        }
        SysUser sysUser = baseMapper.selectById(id);
        List<SysRole> roleList = sysRoleMapper.findByUserId(id);
        sysUser.setRoleList(roleList);
        sysUser.setRoleIds(sysUser.getRoleList());
        return sysUser;
    }

    @Override
    public IPage<SysUser> selectPage(Page<SysUser> page, SysUser sysUser) {
        return baseMapper.selectPage(page, sysUser);
    }

    @Override
    public SysUser findByMobile(String mobile) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", mobile);
        return getBaseMapper().selectOne(queryWrapper);
    }

    @Override
    public SysUser findByName(String name) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", name);
        return getBaseMapper().selectOne(queryWrapper);
    }

    /**
     * 修改用户信息
     *
     * @param sysUserBo
     * @return
     */
    @Override
    public Boolean saveOrUpdateUserBo(SysUserBo sysUserBo) {
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(sysUserBo, sysUser);
        return this.saveOrUpdate(sysUser);
    }

    /**
     * 分页条件查询用户的文章信息
     *
     * @param userArticleQo
     * @return
     */
    @Override
    public PageResult<UserArticleVo> articlePageQuery(UserArticleQo userArticleQo) {
        IPage<UserArticleVo> iPage = PageUtil.createIPage(userArticleQo);
        PageResult<UserArticleVo> userArticleVoPageResult = this.getBaseMapper().articlePageQuery(userArticleQo, iPage);
        return userArticleVoPageResult;
    }

    @Override
    public PageResult<UserQuestionVo> questionPageQuery(UserArticleQo userArticleQo) {
        IPage<UserQuestionVo> iPage = PageUtil.createIPage(userArticleQo);
        PageResult<UserQuestionVo> userArticleVoPageResult = this.getBaseMapper().questionPageQuery(userArticleQo, iPage);
        return userArticleVoPageResult;
    }

    /**
     * 校验旧密码是否正确
     *
     * @param checkOldPasswordBo
     * @return
     */
    @Override
    public ResultInfoFactory checkOldPassword(CheckOldPasswordBo checkOldPasswordBo) {
        SysUser sysUser = this.getBaseMapper().selectById(checkOldPasswordBo.getUserId());
        boolean matches = passwordEncoder.matches(checkOldPasswordBo.getOldPassword(), sysUser.getPassword());
        return matches == true ? ResultInfoFactory.success() : ResultInfoFactory.failed();
    }

    /**
     * 修改密码
     * @param checkOldPasswordBo
     * @return
     */
    @Override
    public ResultInfoFactory updatePassword(CheckOldPasswordBo checkOldPasswordBo) {
        String encode = passwordEncoder.encode(checkOldPasswordBo.getNewPassword());
        SysUser sysUser = new SysUser();
        sysUser.setId(checkOldPasswordBo.getUserId());
        sysUser.setPassword(encode);
        boolean flag = this.saveOrUpdate(sysUser);
        return flag == true ? ResultInfoFactory.success() : ResultInfoFactory.failed();
    }
}
